import {
    apiAddSystemUser,
    apiEditSystemUser,
    apiInfoSystemUser,
    apiListSystemUser,
    apiDeleteSystemUser,
    apiEditPasswordSystemUser,
} from "~/api/user";
import Sortable from "sortablejs";

import useCommon from "~/composables/useCommon";
const { isMobile } = useCommon();

let loading = ref(false);
let userList = ref([]);
let searchKey = ref('');
export default function useUserList(router) {
    // 添加存储源
    const addUser = () => {
        router.push('/admin/user-edit');
    }

    // 编辑存储源
    const editUser = (row) => {
        router.push('/admin/user-edit/' + row.id);
    }

    // 删除存储源
    const deleteUser = (row) => {
        ElMessageBox.confirm('是否确认删除？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            callback: action => {
                if (action === 'confirm') {
                    apiDeleteSystemUser(row.id).then((response) => {
                        ElMessage.success('删除成功');
                        init();
                    });
                }
            }
        });
    }

    // 响应关闭操作提示.
    const handleClose = (done) => {
        ElMessageBox.confirm('是否确认关闭？关闭后填写的数据不会保留。', {
            type: 'warning',
        }).then(_ => {
            done();
        }).catch(_ => {
        });
    }

    // 跳转到文件夹密码设置
    const showPasswordPage = (row) => {
        router.push('/admin/user-password/' + row.id);
    }

    // 响应操作指令
    const handleOperator = (command) => {
        switch (command.operator) {
            case "edit": editUser(command.user); break;
            case "add": addUser(command.user); break;
            case "pwdManager": showPasswordPage(command.user); break;
            case "delete": deleteUser(command.user); break;
        }
    }

    // 设置可拖动排序
    const setSort = () => {
        const el = document.querySelector('.user-container')
        Sortable.create(el, {
            draggable: '.user-item',
            filter: '.add-user-btn',
            delay: isMobile.value ? 300 : 0,
            onEnd: e => {
                if (e.oldIndex === e.newIndex) {
                    return;
                }

                const currRow = userList.value.splice(e.oldIndex, 1)[0];
                userList.value.splice(e.newIndex, 0, currRow)

                storageSortReq(userList.value).then(() => {
                    ElMessage.success('调整排序成功');
                });
            }
        })
    }

    // 初始化
    const init = () => {
        loading.value = true;
        apiListSystemUser({}).then((response) => {
            userList.value = response.data;
            setSort();
            loading.value = false;
        });
    }

    // 存储源列表计算属性, 用于显示右上角搜索框对应的搜索结果.
    const userListSearchResult = computed(() => {
        if (searchKey.value === '') {
            return userList.value;
        }

        // 如果名字或备注或存储源类型包含输入关键字，则作为检索结果.
        return userList.value.filter((item) => {
            if (item.username && item.username.toLowerCase().indexOf(searchKey.value.toLowerCase()) !== -1) {
                return true;
            }
            if (item.nickname && item.nickname.toLowerCase().indexOf(searchKey.value.toLowerCase()) !== -1) {
                return true;
            }
            return false;
        });
    })


    return {
        init, loading,
        searchKey, userListSearchResult,
        handleOperator,
        addUser, editUser, deleteUser, handleClose, showPasswordPage,
    }
}
